package com.fanrui.code.family;

import java.util.Collection;
import java.util.Date;
import java.util.Iterator;

import com.fanrui.code.dao.FamilyListDao;
import com.fanrui.code.entity.Family;
import com.fanrui.code.entity.FamilyList;
import com.fanrui.code.message.PlayerSession;
import com.fanrui.code.message.PlayerSessions;
import com.fanrui.code.player.Player;
import com.fanrui.code.player.PlayerManager;
import com.fanrui.code.util.core.DateUtil;
import com.fanrui.proto.cmd.FamilyJobPower;
import com.fanrui.proto.cmd.FamilyTrendsType;
import com.fanrui.proto.cmd.NotifyHaveOneJoinFamily;
import com.fanrui.proto.cmd.ReqAMemberUpgradePosition;
import com.fanrui.proto.cmd.ReqAMemberUpgradePosition.PositonType;
import com.fanrui.proto.cmd.ResGetPlayerInfo;
import com.fanrui.proto.cmd.ResJoinFamily.Result;
import com.fanrui.proto.cmd.ResRemoveMember;

public class FamilyManager {
	// singleton
	private FamilyManager() {
	}

	private static class FamilyManagerSingleton {
		private static FamilyManager instance = new FamilyManager();
	}

	public static FamilyManager getInstance() {
		return FamilyManagerSingleton.instance;
	}

	public Collection<FamilyEntity> findAllFamily() {
		return FamilyDao.getInstance().findAll();
	}

//	public void loadAllFamilyRoom() {
//			// 加载俱乐部麻将房间
//			Iterator<MahjongBaseRoomConfig> mahjongConfigList = fe.getMahjongConfigList().iterator();
//			while(mahjongConfigList.hasNext()){
//				MahjongBaseRoomConfig c = mahjongConfigList.next();
//				for (int i = 0; i < 2; i++) {
//					if(!fe.createClubRoomConsume(c, false)) {
//						mahjongConfigList = fe.getMahjongConfigList().iterator();
//						break;
//					}
//				}
//			}
//		}

//	// 申请退出家族
//		public Result exitFamily(Player player, int familyId) {
//			// 查找对应的家族是否存在
//			FamilyEntity family = FamilyDao.getInstance().findById(familyId);
//			if (family != null) {
//				// 添加到申请列表中
//				if (player.checkHavaClub(familyId) || !family.addExitToList(player)) {
//					return Result.Joined;
//				}
//				return Result.Success;
//			}
//				else {
//					return Result.FamilyNotExist;
//				}
//		}
	// 加入家族
	public Result joinFamily(Player player, int familyId) {
		// 查找对应的家族是否存在
		FamilyEntity family = FamilyDao.getInstance().findById(familyId);
		if (family != null) {
			if (family.getStatus()==0) {
					// 添加到公会成员中
				    Player member = PlayerManager.getInstance().findOrCreatePlayer(player.getId());
					FamilyList fl = new FamilyList();
					fl.setPlayerId(member.getId());
					fl.setClubId(familyId);
					fl.setJob(3);
					fl.setJointime(new Date());
					fl.setClubIncome(0l);
					FamilyListDao.getInstance().insert(fl);
					family.addFamilyMember(member);
					member.setFamilyData(family);
					member.addClubToList(family);
					member.save();
					// 通知玩家已加入家族
					PlayerSession session = PlayerSessions.getPlayerSession(player.getId());
					if (session != null) {
						ResGetPlayerInfo.Builder notify = ResGetPlayerInfo.newBuilder();
						notify.setPlayerInfo(member.toCmd());
						session.send(notify.build());
					}

					// 添加到动态
					FamilyTrends familyTreads = new FamilyTrends();
					familyTreads.setPlayerId(player.getId());
					familyTreads.setTime(System.currentTimeMillis());
					familyTreads.setType(FamilyTrendsType.FTT_Join);
					familyTreads.setExpandStr(String.format("玩家%s已加入家族", player.getId()));
					family.addTrendsList(familyTreads);
					family.save();
				// 从申请列表中移除
					family.removeToApplyList(member);
					family.save();
			}else if (family.getStatus()==1) {
			// 是否满足加入家族的条件
//			if (!ConditionManager.checkPlayerCondition(player,
//					ParameterConfigManager.getInstance().getIntParameter(EParameterType.JoinFamilyCondition))) {
//				return Result.Condtion;
//			}
			// 添加到申请列表中
			if (player.checkHavaClub(familyId) || !family.addApplyToList(player)) {
				return Result.Joined;
			}
			// 如果家族族长在线通知族长有人加入了
			PlayerSession session = PlayerSessions.getPlayerSession(family.getOwer().getId());
			if (session != null) {
				NotifyHaveOneJoinFamily.Builder notify = NotifyHaveOneJoinFamily.newBuilder();
				notify.setJoinMember(player.toSimpleCmd());
				session.send(notify.build());
			}
			return Result.Success;
		}
			else {
				return Result.Condtion;
			}
		}
		return Result.FamilyNotExist;
	}

	/**
	 * 同意玩家加入家族
	 */
	public com.fanrui.proto.cmd.ResAgreeJoin.Result agreeJoinFamily(Player player, long aplyMemberId, boolean agree) {
		FamilyEntity familyEntity = player.getFamilyData();
		if (familyEntity != null && familyEntity.getApplyList() != null
				&& familyEntity.getApplyList().containsKey(aplyMemberId)) {
			// 获取操作玩家是否有该权限
			// int jobId = 2;
			// for(FamilyMember fm : familyEntity.getMembers().values()) {
			// if(player.getId() == fm.getPlayer().getId()) {
			// jobId = fm.getJobId();
			// }
			// }
			// boolean iscan = FamilyJobConfig.getInstance().isCanOperation(jobId, 3);
			// if(!iscan) {
			// return com.fanrui.proto.cmd.ResAgreeJoin.Result.LimitedAuthority;
			// }
			if (!familyEntity.checkJobPower(player.getId(), FamilyJobPower.MemberManager)) {
				return com.fanrui.proto.cmd.ResAgreeJoin.Result.LimitedAuthority;
			}
			// 查找同意加入的玩家
			Player member = PlayerManager.getInstance().findOrCreatePlayer(aplyMemberId);
			// 判断玩家是否已经加入家族
			if (member.checkHavaClub(player.getFamilyId())) {
				// 从申请列表中移除
				familyEntity.removeToApplyList(member);
				familyEntity.save();
				return com.fanrui.proto.cmd.ResAgreeJoin.Result.PlayerHaveFamily;
			}
			if (member != null) {
				if (agree) {
					// 添加到公会成员中
					FamilyList fl = new FamilyList();
					fl.setPlayerId(member.getId());
					fl.setClubId(familyEntity.getId());
					fl.setJob(3);
					fl.setJointime(new Date());
					fl.setClubIncome(0l);
					fl.setStatus((short)1);
					FamilyListDao.getInstance().insert(fl);
					familyEntity.addFamilyMember(member);
					member.setFamilyData(familyEntity);
					member.addClubToList(familyEntity);
					member.save();
					// 通知玩家已加入家族
					PlayerSession session = PlayerSessions.getPlayerSession(aplyMemberId);
					if (session != null) {
						ResGetPlayerInfo.Builder notify = ResGetPlayerInfo.newBuilder();
						notify.setPlayerInfo(member.toCmd());
						session.send(notify.build());
					}

					// 添加到动态
					FamilyTrends familyTreads = new FamilyTrends();
					familyTreads.setPlayerId(aplyMemberId);
					familyTreads.setTime(System.currentTimeMillis());
					familyTreads.setType(FamilyTrendsType.FTT_Join);
					familyTreads.setExpandStr(String.format("玩家%s已加入家族", aplyMemberId));
					familyEntity.addTrendsList(familyTreads);
					familyEntity.save();
				}
				// 从申请列表中移除
				familyEntity.removeToApplyList(member);
				familyEntity.save();
			}
			return com.fanrui.proto.cmd.ResAgreeJoin.Result.Success;
		} else {
			return com.fanrui.proto.cmd.ResAgreeJoin.Result.PlayerNotExist;
		}
	}
	
	/**
	 * 同意玩家退出家族
	 */
	public com.fanrui.proto.cmd.ResAgreeQuit.Result agreeQuitFamily(Player player, long exitMemberId, boolean agree) {
		FamilyEntity familyEntity = player.getFamilyData();
		if (familyEntity != null && familyEntity.getExitList() != null
				&& familyEntity.getExitList().containsKey(exitMemberId)) {
			// 获取操作玩家是否有该权限
			// int jobId = 2;
			// for(FamilyMember fm : familyEntity.getMembers().values()) {
			// if(player.getId() == fm.getPlayer().getId()) {
			// jobId = fm.getJobId();
			// }
			// }
			// boolean iscan = FamilyJobConfig.getInstance().isCanOperation(jobId, 3);
			// if(!iscan) {
			// return com.fanrui.proto.cmd.ResAgreeJoin.Result.LimitedAuthority;
			// }
			if (!familyEntity.checkJobPower(player.getId(), FamilyJobPower.MemberManager)) {
				return com.fanrui.proto.cmd.ResAgreeQuit.Result.LimitedAuthority;
			}
			// 查找申请退出的玩家
			Player member = PlayerManager.getInstance().findOrCreatePlayer(exitMemberId);
			// 判断玩家是否加入家族
			if (!member.checkHavaClub(player.getFamilyId())) {
				// 从申请列表中移除
				familyEntity.removeToExitList(member);
				familyEntity.save();
				return com.fanrui.proto.cmd.ResAgreeQuit.Result.PlayerDoesNotExist;
			}
			if (member != null) {
				if (agree) {
					Player player1 = PlayerManager.getInstance().findOrCreatePlayer(exitMemberId);
					familyEntity.removeFormFamilyMemberList(familyEntity.getFamilyMemberById(exitMemberId));
					player1.setFamilyData(null);
					player1.removeToClubList(familyEntity);
					player1.save();
					// 添加到动态
					FamilyTrends familyTreads = new FamilyTrends();
					familyTreads.setPlayerId(player.getId());
					familyTreads.setTime(System.currentTimeMillis());
					familyTreads.setType(FamilyTrendsType.FTT_Exit);
					familyTreads.setExpandStr(String.format("玩家%s已退出家族", player.getId()));
					familyEntity.addTrendsList(familyTreads);
					familyEntity.save();
				}
				// 从申请列表中移除
				familyEntity.removeToExitList(member);
				familyEntity.save();
			}
			return com.fanrui.proto.cmd.ResAgreeQuit.Result.Success;
		} else {
			return com.fanrui.proto.cmd.ResAgreeQuit.Result.PlayerNotExist;
		}
	}
	

	/**
	 * 踢出家族
	 */
	public ResRemoveMember.Result removeMemeberFromFamily(Player player, long memberId) {
		FamilyEntity familyEntity = player.getFamilyData();

		if (familyEntity != null && familyEntity.getMembers() != null && familyEntity.getMembers().containsKey(memberId)
				&& player.getId() != memberId) {
			// 获取操作玩家是否有该权限 不能踢出比自己权限高或者相同的玩家
			// int jobId = 2;
			// int tiJobId = 2;
			// for(FamilyMember fm : familyEntity.getMembers().values()) {
			// if(player.getId() == fm.getPlayer().getId()) {
			// jobId = fm.getJobId();
			// }else if(fm.getPlayer().getId() == memberId) {
			// tiJobId = fm.getJobId();
			// }
			// }
			if (familyEntity.checkJobPower(player.getId(), memberId) != 1) {
				return ResRemoveMember.Result.UnPermission;
			}
			// boolean iscan = FamilyJobConfig.getInstance().isCanOperation(jobId, 4);
			// if(!iscan) {
			// return ResRemoveMember.Result.UnPermission;
			// }
			if (!familyEntity.checkJobPower(player.getId(), FamilyJobPower.MemberManager)) {
				return ResRemoveMember.Result.UnPermission;
			}

			// 查找同意加入的玩家
			Player member = PlayerManager.getInstance().findOrCreatePlayer(memberId);
			if (member != null) {
				familyEntity.removeFormFamilyMemberList(familyEntity.getFamilyMemberById(member.getId()));
				// 添加到动态
				FamilyTrends familyTreads = new FamilyTrends();
				familyTreads.setPlayerId(player.getId());
				familyTreads.setTime(System.currentTimeMillis());
				familyTreads.setType(FamilyTrendsType.FTT_Exit);
				familyTreads.setExpandStr(String.format("玩家%s已退出家族", player.getId()));
				familyEntity.addTrendsList(familyTreads);
				member.setFamilyData(null);
				member.removeToClubList(familyEntity);
				member.save();
				familyEntity.save();
				// 通知玩家已被踢出家族
				PlayerSession session = PlayerSessions.getPlayerSession(memberId);
				if (session != null) {
					ResGetPlayerInfo.Builder notify = ResGetPlayerInfo.newBuilder();
					notify.setPlayerInfo(member.toCmd());
					session.send(notify.build());
				}
			}
			return ResRemoveMember.Result.Success;
		}
		return ResRemoveMember.Result.Other;
	}

	/**
	 * 退出家族
	 */
	public com.fanrui.proto.cmd.ResEixtFamily.Result exitFamily(Player player) {
		FamilyEntity familyEntity = player.getFamilyData();
		if (familyEntity != null) {
			// 族长退出家族 直接解散家族
			if (familyEntity.getOwer().getId() == player.getId()) {
				destoryFamily(familyEntity);
			} else {
				// 查找对应的家族是否存在
				if (familyEntity != null) {
					// 添加到申请列表中
					if (!player.checkHavaClub(familyEntity.getId()) || !familyEntity.addExitToList(player)) {
						return com.fanrui.proto.cmd.ResEixtFamily.Result.Unused;
					}
					return com.fanrui.proto.cmd.ResEixtFamily.Result.Success;
				}
			}

			return com.fanrui.proto.cmd.ResEixtFamily.Result.Success;
		} else {
			return com.fanrui.proto.cmd.ResEixtFamily.Result.Unused;
		}
	}

	/**
	 * 解散家族
	 */
	public void destoryFamily(FamilyEntity familyEntity) {
		if (familyEntity != null) {
			Collection<FamilyMember> list = familyEntity.getMembers().values();
			synchronized (list) {
				Iterator<FamilyMember> iterator = list.iterator();
				while (iterator.hasNext()) {
					FamilyMember fm = iterator.next();
					if (fm != null) {
						FamilyListDao.getInstance().delete(fm.getPlayer().getId(), familyEntity.getId());
						iterator.remove();
						fm.getPlayer().setFamilyData(null);
						fm.getPlayer().removeToClubList(familyEntity);
						fm.getPlayer().save();
					}
				}
			}
			FamilyDao.getInstance().dbDelete(familyEntity.getId());
			// for (FamilyMember player : ) {
			// if (player.getPlayer() != null) {
			//
			// }
			// // 查找同意加入的玩家
			// Player member = PlayerDao.getInstance().createPlayerAndLoad(playerId);
			//// Player member = PlayerDao.getInstance().
			// if (member != null) {
			// member.setFamilyData(null);
			// member.removeClubByKey(familyEntity);
			// member.save();
			// }
			// }
		}
	}

	public synchronized FamilyEntity createFamily(String familyName, long playerId) {
		return FamilyDao.getInstance().createFamilyIFSuccessLoad(cerateBaseUser(familyName, playerId));

	}

	/**
	 * 创建一个默认的家族
	 */
	public Family cerateBaseUser(String familyName, long owerId) {
		Family family = new Family();
		Date createTime = new Date();
		family.setFamilyName(familyName);
		family.setFamilyOwer(owerId);
		family.setFamilyApplyList("");
		family.setFamilyExitList("");
		family.setSuperior(0);
		family.setStatus((short)1);
		family.setFamilyerList("[{playerId:" + owerId + ",job:1,joinTime:" + createTime.getTime() + "}]  ");
		family.setFamilyInfo("");
		family.setFamilyLevel(1);
		family.setFamilyNotice("");
		family.setFamilyCreateTime(createTime);
		return family;
	}

	/**
	 * 统计家族的某日收益 只计算家族成员赢的钱
	 */
	// public long accountFamilyGold(FamilyEntity family, String date) {
	// if (family == null) {
	// return 0;
	// }
	// Collection<FamilyMember> members = family.getMembers().values();
	// long total = 0;
	// if (members != null && !members.isEmpty()) {
	// for (FamilyMember member : members) {
	// if (member.getPlayer() == null || member.getPlayer().getId() ==
	// family.getOwer().getId()) {
	// continue;
	// }
	// Long earing =
	// PlayerLogDao.getInstance().getPlayerAllEarnings(member.getPlayer().getId(),
	// date);
	// if (earing != null) {
	// total += earing;
	// }
	// }
	// }
	// return total;
	// }
	/**
	 * 设置玩家家族职位
	 */
	public String setPlayerClubJob(Player player, ReqAMemberUpgradePosition req) {
		FamilyEntity fe = FamilyDao.getInstance().findById(player.getFamilyId());
		if (fe == null || fe.getOwer().getId() != player.getId()) {
			return "UnPermission";
		}
		Player uplayer = PlayerManager.getInstance().findOrCreatePlayer(req.getUid());
		if (uplayer == null) {
			return "UnPermission";
		}

		PositonType pt = req.getPt();
		FamilyMember fm = fe.getMemberByIdOrNickname(req.getUid() + "");

		if (fm == null) {
			return "NoOneInQuan";
		} else {
			if (pt == PositonType.LevelOne) {
				FamilyMember f = fe.getMemberByIdOrNickname(player.getId() + "");
				f.setFamilyJob(PositonType.LevelThree_VALUE + 1);
				fe.setOwer(uplayer);
				f.save();
				fe.save();
				fm.setFamilyJob(PositonType.LevelOne_VALUE + 1);
			} else {
				fm.setFamilyJob(pt.getNumber() + 1);
			}
		}

		try {
			fm.save();
		} catch (Exception e) {
			return "UnPermission";
		}
		return "Success";
	}

	/**
	 * 判断家族是否存在
	 */
	public boolean checkHasFamily(int id) {
		FamilyEntity entity = FamilyDao.getInstance().findById(id);
		return entity != null;
	}

	public static void main(String[] args) {
		// Date date = DateUtil.getYesterday();
		// SimpleDateFormat format = new SimpleDateFormat("YYYY-MM-dd");
		// System.out.println(format.format(date));

		long time = DateUtil.getTodayTimeDigitalSumVariation("00:00:00");
		System.out.println(time);
	}

	/**
	 * 玩家通过url 加入家族
	 */
	public static String joinFamilyByUrl(int familyId, long userId) {

		Player player = PlayerManager.getInstance().findOrCreatePlayer(userId);

		if (player == null) {
			return "PlayerNotExit";
		}

		FamilyManager fm = new FamilyManager();
		Result result = fm.joinFamily(player, (int) familyId);

		if (result.equals(Result.FamilyNotExist)) {
			return "FamilyNotExit";
		}
		if (result.equals(Result.Condtion)) {
			return "FamilyNotExit";
		}
		if (result.equals(Result.Joined)) {
			return "PlayerInFamily";
		}
		if (result.equals(Result.Success)) {
			return "Success";
		}

		return "";
		// FamilyEntity entity = FamilyDao.getInstance().findById(familyId);
		// if(entity == null){
		// return "FamilyNotExit";
		// }
		// // 获取玩家对象
		// Player player = PlayerManager.getInstance().findOrCreatePlayer(userId);
		// if(player == null){
		// return "PlayerNotExit";
		// }
		//
		//// if(player.getFamilyData() != null || !( player.getFamily() == null ||
		// player.getFamily() == -1)){
		//// return "PlayerInFamily";
		//// }
		//
		// // 已经加入过，不能再加入
		// if(player.checkHavaClub(familyId)) {
		// return "PlayerInFamily";
		// }
		//
		// // 添加到公会成员中
		// entity.addFamilyMember(player);
		// player.setFamilyData(entity);
		// player.addClubToList(entity);
		//
		// // 添加到动态
		// FamilyTrends familyTreads = new FamilyTrends();
		// familyTreads.setPlayerId(player.getId());
		// familyTreads.setTime(System.currentTimeMillis());
		// familyTreads.setType(FamilyTrendsType.FTT_Join);
		// familyTreads.setExpandStr(String.format("玩家%s已加入家族", player.getId()));
		// entity.save();
		// player.save();
		//
		// return "Success";
	}
}
